package ch.unifr.diva.multimodals.spherex;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.View;

public class TestingThread extends Thread {
	public static final int SLEEP_BETWEEN_TESTS=2000;
	NetConfigurationActivity act;
	Runner r = new Runner();
	private boolean running;
	private Handler handler;
	
	public TestingThread(NetConfigurationActivity act){
		this.act=act;
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				try {
					if (r.get())
						;//Ok
					else{
						interrupt();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
			}
			
		};
	}
	
	public void setRunning(boolean running){
		this.running=running;
	}
	
	@Override
	public void start() {
		super.start();
		r = new Runner();
		r.execute(act);
	}

	@Override
	public void run() {
		super.run();
		while(running){
			if(r.getStatus()==AsyncTask.Status.FINISHED){
				//Only if runner is not running
				r = new Runner();
				r.execute(act);
			}
		try {
			Thread.sleep(SLEEP_BETWEEN_TESTS);
		} catch (InterruptedException e) {
			e.printStackTrace();
			running=false;
			interrupt();
		}
		handler.sendMessage(handler.obtainMessage());
	}
	}

	@Override
	public void interrupt() {
		super.interrupt();
		try {
			act.socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
